#include "spell.h"
#include <string>
StrategyFactory::CGarbo StrategyFactory::Garbo;
std::string 
replace(std::string old_str,std::string sub_str,std::string new_str){
  std::string dst_str = old_str;
  std::string::size_type pos = 0;
  std::vector<int>index;
  while((pos = dst_str.find(sub_str),pos) != std::string::npos)  
  {
     dst_str.replace(pos, sub_str.length(), new_str);
  }
  return dst_str;
}
SpellChecker::~SpellChecker(){
  delete sf;
}
LangStrategy 
*StrategyFactory::create_lang_strategy(){
  switch(environ->lang){
    case ENG:
      return LocalStrategy::instance(ENG_LEXICON);
      break;
    case FRA:
      return LocalStrategy::instance(FRA_LEXICON);
      break;
    default:
      return LocalStrategy::instance(ENG_LEXICON);
      break;
  }
}
FormatStrategy 
*StrategyFactory::create_format_strategy(){
   switch(environ->format){
     case TXT:
        return TXTStrategy::instance();
        break;
     case XML:
        return XMLStrategy::instance();
        break;
     default:
        return TXTStrategy::instance();
        break;
   }
}
std::vector<std::string> 
SpellChecker::spell(std::string context){
  LangStrategy *ls = sf->create_lang_strategy();
  FormatStrategy *fs = sf->create_format_strategy();
  std::string filt_context = fs->filt(context);
  std::vector<std::string> ret = ls->check(filt_context);
  return ret;
}
std::string 
SPACommand::execute(){
  std::vector<std::string> faults = sc->spell(editor->get_text());
  std::string context = editor->get_text();
  for(auto fault:faults){
    std::string new_str = "*[";
    new_str += fault + "]";
    context = replace(context,fault,"*&^#");
    context = replace(context,"*&^#",new_str);
  }
  return context;
}
void 
SPMCommand::edit(){
  std::vector<std::string> faults = sc->spell(editor->get_text());
  std::string context = editor->get_text();
  for(auto &fault:faults){
    std::string new_str = "";
    context = replace(context,fault,new_str);
  }
  editor->set_text(context);
}
